package chat.aylan.top.database.service;
/**
 * 用户服务
 */

import chat.aylan.top.database.entity.UserEntity;
import chat.aylan.top.wind.ManagerWind;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class UserServicce extends BaseService {

    /**
     * 查询用户
     * @param username
     * @return
     */
    public UserEntity selectUserByUsername(String username){

        String sql = "select * from user where username = ?";
        try {
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1,username);
            ResultSet res = statement.executeQuery();
            UserEntity user = null;
            while (res.next()){
               user = new UserEntity();
               user.setId(res.getInt("id"));
               user.setUsername(res.getString("username"));
               user.setPassword(res.getString("password"));
            }
            return user;
        } catch (SQLException e) {
             e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询所有用户
     * @return
     */
    public ArrayList<UserEntity> selectAll(){

        String sql = "select * from user where id !=?";
        try {
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setInt(1,ManagerWind.user.getId());
            ResultSet res = statement.executeQuery();
            ArrayList<UserEntity> list = new ArrayList<>();
            while (res.next()){
                UserEntity user = new UserEntity();
                user.setId(res.getInt("id"));
                user.setUsername(res.getString("username"));
                user.setPassword(res.getString("password"));
                user.setStatus(res.getShort("status"));
                list.add(user);
            }
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 编辑 用户
     * @param user
     * @return
     * @throws SQLException
     */
    public int updateUser(UserEntity user) throws SQLException{
        StringBuffer sql = new StringBuffer("update user set status = ?");
        if(user.getUsername() != null){
           sql.append(",username = ?");
        }
        if(user.getPassword() != null){
            sql.append(",password = ?");
        }
        sql.append(" where id = "+user.getId());
        PreparedStatement statement = connection.prepareStatement(sql.toString());
        statement.setShort(1,user.getStatus());
        if(user.getUsername()!=null){
            statement.setString(2,user.getUsername());
        }
        if(user.getPassword()!=null){
            statement.setString(3,user.getPassword());
        }
        return statement.executeUpdate();
    }
}
